package com.order.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.order.constant.PasswordConstant;
import com.order.constant.StatusConstant;
import com.order.dto.ConsumerDTO;
import com.order.dto.ConsumerPageQueryDTO;
import com.order.entity.User;
import com.order.mapper.UserMapper;
import com.order.result.PageResult;
import com.order.service.ConsumerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 客户分页查询
     * @return
     */
    @Override
    public PageResult pageQuery(ConsumerPageQueryDTO consumerPageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(consumerPageQueryDTO.getPage(),consumerPageQueryDTO.getPageSize());

        Page<User> page =userMapper.pageQuery(consumerPageQueryDTO);

        long total = page.getTotal();
        List<User> records = page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 新增客户
     * @param consumerDTO
     * @return
     */
    public void save(ConsumerDTO consumerDTO) {

        System.out.println("当前线程的id:" + Thread.currentThread().getId());

        User user = new User();

        //对象属性拷贝
        BeanUtils.copyProperties(consumerDTO,user);

        //设置剩余属性
        user.setStatus(StatusConstant.ENABLE);
        user.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        userMapper.insert(user);
    }

    /**
     * 启用禁用客户账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, long id) {
        User user = User.builder().status(status).id(id).build();
        userMapper.update(user);
    }

    /**
     * 根据ID查询客户
     * @param id
     * @return
     */
    @Override
    public User getById(long id) {
        User user = userMapper.getById(id);
        user.setPassword("******");
        return user;
    }

    /**
     * 编辑员工信息
     * @param consumerDTO
     */
    public void update(ConsumerDTO consumerDTO) {

        User user = new User();
        BeanUtils.copyProperties(consumerDTO,user);

        userMapper.update(user);

    }

    /**
     * 客户批量删除
     * @param ids
     */
    @Transactional
    public void deleteUser(List<Long> ids) {
        userMapper.deleteByIds(ids);
    }

}
